package com.wosai.teach.handler;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.android.agnetty.core.event.ExceptionEvent;
import com.android.agnetty.core.event.MessageEvent;
import com.android.agnetty.future.http.HttpHandler;
import com.android.agnetty.utils.LogUtil;
import com.wosai.teach.dao.ExperimentDao;
import com.wosai.teach.pojo.Experiment;
import com.wosai.teach.pojo.JsonResult;
import com.wosai.teach.utils.GodUtils;

public class ExperimentListHandler extends HttpHandler {

	public ExperimentListHandler(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean onCompress(MessageEvent arg0) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDecode(MessageEvent arg0) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onDecompress(MessageEvent arg0) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onEncode(MessageEvent arg0) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onHandle(MessageEvent evt) throws Exception {
		String response = new String((byte[]) evt.getData(), "utf-8");
		LogUtil.d(LoginHandler.class.getCanonicalName() + response);
		if (!TextUtils.isEmpty(response)) {
			System.out.println(response);
			JsonResult jr = JSON.parseObject(response, JsonResult.class);
			if (jr.getResult() == 0) {
				List<Experiment> expList = JSON.parseArray(jr.getObject()
						.toString(), Experiment.class);
				ExperimentDao expDao = new ExperimentDao();
				if (!GodUtils.CheckNull(expList)) {
					for (Experiment exp : expList) {
						Experiment expDb = expDao.getExperimentByExpId(exp
								.getExpId());
						if (expDb != null) {
							exp.setStatus(expDb.getStatus());
						}
					}
					expDao.deleteAllDb();
					for (Experiment exp : expList) {
						exp.save();
					}
				}
				evt.getFuture().commitComplete(true);
			} else {
				evt.getFuture().commitComplete(false);
			}
		}
	}

	@Override
	public void onDispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onException(ExceptionEvent arg0) {
		// TODO Auto-generated method stub

	}

}
